package com.easy.carl.algorithm.array.slidingWindow;

/**
 * 209. 长度最小的子数组
 */
public class MinSubArrayLen209 {
    public int minSubArrayLen(int target, int[] nums) {
        //记录总和
        int sum=0;
        //最小长度初始值为Integer最大值
        int minLength=Integer.MAX_VALUE;
        //窗口的左边界
        int j=0;
        //窗口的右边界
        for (int i = 0; i < nums.length; i++) {
            sum+=nums[i];
            //总和大于目标值
            while (sum>=target){
                //记录窗口长度
                minLength=Math.min(minLength,i-j+1);
                //总和减去左边界的值，缩小窗口
                sum-=nums[j++];
            }
        }
        //System.out.println(minLength);
        return minLength==Integer.MAX_VALUE?0:minLength;
    }

    /**
     * 暴力解法
     * @param target
     * @param nums
     * @return
     */
    public int minSubArrayLen1(int target, int[] nums) {
        //最小长度
        Integer minLen = Integer.MAX_VALUE;
        //以i开始的索引的最小长度
        for (int i = 0; i < nums.length; i++) {
            int sum=0;
            for (int j = i; j < nums.length ; j++) {
                sum+=nums[j];
                if (sum>=target){
                    minLen=Math.min(minLen,j-i+1);
                    break;
                }
            }
        }
        //System.out.println(minLen);
        return minLen==Integer.MAX_VALUE?0:minLen;
    }


    public static void main(String[] args) {
        MinSubArrayLen209 minSubArrayLen209 = new MinSubArrayLen209();
        minSubArrayLen209.minSubArrayLen1(7,new int[]{
                2,3,1,2,4,3});
    }
}
